package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.AttrGroupService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrResVo;
import com.atguigu.gulimall.product.vo.AttrVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    /**
     *商品属性类型
     */
    public static final String PRODUCT_ATTR_TYPE_BASE = "base";
    public static final String PRODUCT_ATTR_TYPE_SALE = "sale";

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void saveAttr(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        // 保存属性
        this.save(attrEntity);
        // 销售属性 没有分组
        if (attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode() || attrVO.getAttrGroupId() == null) {
            return;
        }
        // 保存属性和属性分组关联关系
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationEntity.setAttrGroupId(attrVO.getAttrGroupId());
        attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
    }

    @Override
    public PageUtils queryAttrPage(String type, Long catelogId, Map<String, Object> params) {
        LambdaQueryWrapper<AttrEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(AttrEntity::getAttrType,
                PRODUCT_ATTR_TYPE_BASE.equalsIgnoreCase(type) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            wrapper.eq(AttrEntity::getCatelogId, catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNoneBlank(key)) {
            wrapper.and(w -> w.eq(AttrEntity::getAttrId, key)
                    .or()
                    .like(AttrEntity::getAttrName, key));
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        List<AttrEntity> records = page.getRecords();
        // 封装返回集合
        List<AttrResVo> resVos = records.stream()
                .map(attrEntity -> {
                    AttrResVo attrResVo = new AttrResVo();
                    BeanUtils.copyProperties(attrEntity, attrResVo);
                    // 设置所属分类名
                    CategoryEntity categoryEntity = categoryService.getById(attrResVo.getCatelogId());
                    if (categoryEntity != null) {
                        attrResVo.setCatelogName(categoryEntity.getName());
                    }
                    // 基本属性才需要设置 属性分组
                    if (PRODUCT_ATTR_TYPE_BASE.equalsIgnoreCase(type)) {
                        // 设置属性分组名
                        AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationService.getOne(Wrappers
                                .<AttrAttrgroupRelationEntity>lambdaQuery()
                                .eq(AttrAttrgroupRelationEntity::getAttrId, attrResVo.getAttrId()));
                        if (attrgroupRelationEntity != null && attrgroupRelationEntity.getAttrGroupId() != null) {
                            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupRelationEntity.getAttrGroupId());
                            if (attrGroupEntity != null) {
                                attrResVo.setGroupName(attrGroupEntity.getAttrGroupName());
                            }
                        }
                    }
                    return attrResVo;
                }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(resVos);
        return pageUtils;
    }

    @Override
    public AttrResVo getAttrDetailById(Long attrId) {
        AttrResVo resVo = new AttrResVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, resVo);

        // 1. 设置所属分类 全路径
        List<Long> catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        resVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        resVo.setCatelogName(categoryEntity.getName());
        // 销售属性 没有分组
        if (resVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()) {
            return resVo;
        }
        // 2. 设置所属分组
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId()));
        if (relationEntity != null) {
            resVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                resVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
        return resVo;
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void updateAttrDetailById(AttrVO attrVO) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVO, attrEntity);
        // 修改属性
        this.updateById(attrEntity);
        // 销售属性 没有分组
        if (attrVO.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()) {
            return;
        }
        // 修改或新增 属性 属性分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrId(attrVO.getAttrId());
        relationEntity.setAttrGroupId(attrVO.getAttrGroupId());
        attrAttrgroupRelationService.saveOrUpdate(relationEntity,
                Wrappers.<AttrAttrgroupRelationEntity>lambdaUpdate()
                        .eq(AttrAttrgroupRelationEntity::getAttrId, relationEntity.getAttrId()));
    }

}
